package com.quwancode.mavenjdbc;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;

/**
 * @description:
 * @author: ChengKai
 * @time: 2023/3/2 10:40
 */
public class DbHelp {

    public static Connection getConnection() {
        Connection con = null; // 声明连接

        try {
            ResourceBundle rb = ResourceBundle.getBundle("dbcfg");
            String driverClass = rb.getString("driverClass");
            String url = rb.getString("url");
            String user = rb.getString("user");
            String password = rb.getString("password");

            Class.forName(driverClass);
            // 声明驱动
            con = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.toString());
        }
        return con; // 返回连接
    }

    public static void release(ResultSet rs, PreparedStatement pstmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    //通用的执行sql方法
    public static List<Object> executeSql(String sql) throws SQLException {

        Connection con = DbHelp.getConnection();
        PreparedStatement pstmt = con.prepareStatement(sql);
        //执行sql语句
        pstmt.execute();
        ResultSet rs = pstmt.getResultSet();

        List<Object> retVal = new ArrayList<>();
        retVal.add(rs);
        retVal.add(pstmt);
        retVal.add(con);
        return retVal;
    }

}
